<template>
  <div class="app-container">
    <el-col>
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px" @submit.native.prevent>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="plus" @click="handleAdd">添加</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">批量删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      highlightCurrentRow
      border
      stripe
      @current-change="handleCurrentChange"
      @selection-change="handleSelectionChange"
      v-dragable="[
        {
          selector: 'thead tr',
          option: {
            animation: 150,
            draggable: '.dragable-col',
            onEnd: (evt) => {
              const startIndex = 0
              const oldIndex = evt.oldIndex - startIndex
              const newIndex = evt.newIndex - startIndex
              if (oldIndex > newIndex) {
                columns.splice(newIndex, 0, columns[oldIndex])
                columns.splice(oldIndex + 1, 1)
              } else {
                columns.splice(newIndex + 1, 0, columns[oldIndex])
                columns.splice(oldIndex, 1)
              }
            }
          }
        }
      ]">
      <el-table-column type="selection" width="50" align="center" :selectable="isRowSelectable" />
      <template v-for="col in columns">
        <el-table-column
          :key="col['prop']"
          :type="col['type']"
          :prop="col['prop']"
          :label="col['label']"
          :width="col['width']"
          :align="col['align']"
          :min-width="col['min-width']"
          :class-name="col['class-name']"
          :show-overflow-tooltip="col['show-overflow-tooltip']"
          v-if="!!col['visible']">
          <template #default="scope" v-if="col['custom-template']">
            <component :is="col['custom-template'](scope)"></component>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <el-dialog :title="title" v-model="open" width="600px" append-to-body draggable>
      <el-form :model="form" ref="formRef" label-width="120px">
        <el-form-item label="省区市" prop="pca">
          <el-cascader
            v-model="form.pca"
            :options="pcaOptions"
            :props="{ value: 'name', label: 'name', children: 'children' }"
            clearable
            placeholder="请选择" />
        </el-form-item>
        <el-form-item label="详细地址" prop="detail">
          <el-input v-model="form.detail" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="是否默认" prop="isdefault">
          <el-radio-group v-model="form.isdefault">
            <el-radio-button v-for="item in isdefaultOptions" :label="item.dictValue">{{ item.dictLabel }}</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button text @click="cancel">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx">
import modal from '@/plugins/modal'
import { vDragable } from 'element-plus-table-dragable'
import { FormInstance, ElMessageBox } from 'element-plus'
import { deepClone } from '@/utils'
import { listShippingAddress, addShippingAddress, updateShippingAddress, delShippingAddress } from '@/api/souvenir/shippingaddress'
import { listUser } from '@/api/system/user'
import { useDicts } from '@/utils/dict'
import { getToken } from '@/utils/auth'
import useUserStore from '@/store/modules/user'

const userStore = useUserStore()
const { sys_yes_no } = useDicts('sys_yes_no')

const isdefaultOptions = sys_yes_no

const pcaOptions = ref([])
const getPcaOptions = () => {
  fetch('/pca-code.json')
    .then((res) => res.json())
    .then((data) => {
      pcaOptions.value = data
    })
}

getPcaOptions()

interface shippingAddress {
  id?: number
  pca: Array<string>
  detail: string
  userId: number
  isdefault: string
}

interface column {
  label?: string
  prop?: string
  type?: string
  width?: string
  align?: string
  'min-width'?: string
  'class-name'?: string
  'show-overflow-tooltip'?: boolean
  'custom-template'?: (scope: any) => {}
  visible: boolean
}

const columns = ref<column[]>([
  {
    prop: 'pca[0]',
    label: '省',
    'class-name': 'dragable-col',
    visible: true
  },
  {
    prop: 'pca[1]',
    label: '市',
    'class-name': 'dragable-col',
    visible: true
  },
  {
    prop: 'pca[2]',
    label: '区',
    'class-name': 'dragable-col',
    visible: true
  },
  {
    prop: 'detail',
    label: '详细地址',
    'class-name': 'dragable-col',
    visible: true
  },
  {
    prop: 'isdefault',
    label: '是否默认',
    visible: true,
    align: 'center',
    'class-name': 'dragable-col',
    'custom-template': (scope) => {
      return (
        <>
          <dict-tag options={isdefaultOptions.value} value={scope.row.isdefault} />
        </>
      )
    }
  },
  {
    prop: 'action',
    label: '操作',
    align: 'center',
    width: '200',
    'custom-template': (scope) => {
      return (
        <>
          <el-button
            text
            icon="edit"
            type="success"
            title="编辑"
            onClick={() => {
              handleUpdate(scope.row)
            }}></el-button>
          <el-button
            text
            icon="delete"
            type="danger"
            title="删除"
            onClick={() => {
              handleDelete(scope.row)
            }}></el-button>
        </>
      )
    },
    visible: true
  }
])

const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const loading = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  userId: userStore.userId
})

const list = ref<shippingAddress[]>()
const getList = async () => {
  loading.value = true
  try {
    const { data } = await listShippingAddress(queryParams.value)
    list.value = data.result
    total.value = data.totalNum
    loading.value = false
  } catch (error) {
    console.error(error)
    loading.value = false
  }
  loading.value = false
}

const queryRef = ref<FormInstance>()

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
}
/** 重置按钮操作 */
const resetQuery = () => {
  queryRef.value?.resetFields()
  getList()
}

const currentRow = ref()
const handleCurrentChange = (val) => {
  currentRow.value = val
}
/** 选择条数  */
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

const isRowSelectable = (row, index) => {
  return row.isdefault === isdefaultOptions.value.find((item) => item.dictLabel !== '是').dictValue
}

const form = ref<shippingAddress>({
  id: undefined,
  pca: [],
  detail: '',
  userId: userStore.userId,
  isdefault: 'N'
})
const title = ref('')
const open = ref(false)
const formRef = ref<FormInstance>()

const reset = (isUpdate: boolean, row?: any) => {
  if (isUpdate) {
    form.value = deepClone(row)
  } else {
    form.value = {
      id: undefined,
      pca: [],
      detail: '',
      userId: userStore.userId,
      isdefault: 'N'
    }
  }
}

const cancel = () => {
  open.value = false
  reset(false)
}
const handleConfirm = async () => {
  await formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        if (title.value === '新增收货地址') {
          const { data } = await addShippingAddress(form.value)
          if (data) {
            modal.msgSuccess('新增成功')
          }
        } else {
          const { data } = await updateShippingAddress(form.value)
          if (data) {
            modal.msgSuccess('编辑成功')
          }
        }
      } catch (error) {
        console.error(error)
        if (title.value === '新增收货地址') {
          modal.msgError('新增失败')
        } else {
          modal.msgError('编辑失败')
        }
      }
      open.value = false
      getList()
    }
  })
}

const handleAdd = async () => {
  title.value = '新增收货地址'
  open.value = true
  formRef.value?.resetFields()
  reset(false)
  formRef.value?.clearValidate()
}

const handleUpdate = async (row) => {
  try {
    title.value = '编辑收货地址'
    open.value = true
    formRef.value?.resetFields()
    reset(true, row)
    formRef.value?.clearValidate()
  } catch (error) {}
}
const handleDelete = async (row) => {
  try {
    const delIds = row.id ? [row.id] : ids.value
    await modal.confirm(`是否确认删除所选择的数据项？`)
    try {
      await delShippingAddress(delIds)
      modal.msgSuccess('删除成功')
    } catch (error) {
      console.error(error)
      modal.msgError('删除失败')
    }
    getList()
  } catch (error) {}
}

getList()
</script>

<style scoped></style>
